<script setup lang="ts">
import { watch, ref, computed, onUnmounted, inject, toRaw } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import { onMounted } from "vue";
import AlertDialog from "../common/alertDialog.vue";

import { useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import { queryMonitor } from "@/api/visual/visualConfig";
import useFlv from "@visual/utils/useFlv";
const isVisualEditer = inject("isVisualEditer", false);
const positionCode = inject("positionCode", ref(""));
const pageType = inject("pageType", ref(""));

const router = useRouter();
const cameraUrl = ref("");
const flvRef = ref();
const { getFlv, videoClick, destoryVideo } = useFlv({ videoRef: flvRef, cameraUrl: cameraUrl });

const alertShow = ref(false);
const alarmInfo = ref({});
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
import useWs from "@/hooks/useWs";
import dayjs from "dayjs";
defineOptions({
  name: "tableAlert"
});
const isCollapsed = ref(false);
const statusMap = ref({
  UNDO: "未处理",
  DONE: "已处理"
});
const tagBgColorList = {
  一级报警: "#E02B2B",
  二级报警: "#FF771E",
  三级报警: "#F1B11A",
  四级报警: "#4A9BFF"
};
const tagLabelList = {
  一级报警: "一级",
  二级报警: "二级",
  三级报警: "三级",
  四级报警: "四级"
};
const props = withDefaults(
  defineProps<{
    propValue?: {
      tableData: Array<any>;
      title?: string;
      collapsed?: boolean;
      iconName?: string;
      needAlert?: boolean;
      ext1?: string;
    };
  }>(),
  {
    propValue: () => ({
      tableData: [],
      title: "",
      collapsed: false,
      iconName: "alert",
      needAlert: false,
      ext1: "[]"
    })
  }
);
const realTabelData = ref([]);
const isAnalyse = ref(false);
const selectCamera = ref();
const selectCameraOption = ref([]);
let destorySoc = null;
const dealposition = row => {
  try {
    return row?.twinName;
  } catch (e) {
    return "";
  }
};
const dealStatus = row => {
  try {
    return statusMap[row?.status] ? statusMap[row?.status] : "";
  } catch (e) {
    return "";
  }
};
const handleLocation = row => {
  try {
    let { twinId } = row;
    router.push({
      path: "/all/visual/template",
      query: {
        compEmitData: twinId
      }
    });
  } catch (e) {
    console.error(e);
  }
  console.log("跳转到对应位置", row.twinId);
};
let buffer = [];
let timer = null;
function updateTable(data) {
  const { accountNameList, roomId, buildingId, floorId, factoryId, className } = data;
  if ((pageType.value === "EQP" && data.twinId === positionCode.value) || pageType.value !== "EQP") {
    let userClassName = JSON.parse(localStorage.getItem("classList")) || [];
    if (userClassName?.length > 0) {
      const res = [];
      userClassName.forEach(item => {
        res.push(item.code);
      });
      userClassName = res;
    }
    if (!userClassName.includes(className)) return;
    if (!accountNameList.includes(userInfo.username)) return;
    const facCode = localStorage.getItem("facCode") || "";
    if (facCode && facCode !== factoryId) return;
    if (pageType.value === "ROOM") {
      try {
        let ext1 = JSON.parse(props.propValue.ext1);
        if (ext1.length === 0) return;
        if (!ext1.includes(data.twinId)) return;
      } catch (e) {
        console.error(e);
      }
    } else if (pageType.value === "BUILD") {
      if (positionCode.value !== buildingId) return;
    } else if (pageType.value === "FLOOR") {
      if (positionCode.value !== floorId) return;
    } else if (pageType.value === "FAC") {
      if (positionCode.value !== factoryId) return;
    }
    buffer.unshift(data);
    if (timer) return;
    timer = setTimeout(() => {
      realTabelData.value = buffer.concat(realTabelData.value);
      buffer = [];
      alertMessage();
      timer = null;
    }, 2000);
  }
}
function alertMessage() {
  if (realTabelData.value.length > 0 && props.propValue.needAlert && pageType.value === "EQP") {
    try {
      const filterArr = realTabelData.value.filter(item => item.alarmStatus == "ON");
      const first = getLatestObject(filterArr, "alarmTime");
      if (first) {
        const { alarmTime, alarmContent } = first;
        PxMessage.closeAll();
        let msg = alarmTime ? `${alarmTime}  ${alarmContent}` : alarmContent;
        PxMessage({
          showClose: true,
          message: msg,
          type: "error",
          duration: 0
        });
      }
    } catch (error) {
      console.error("设备报警推送报错-->", error);
    }
  }
}
function getLatestObject(arr, timeKey) {
  if (!arr || arr.length === 0) return undefined;

  return arr.reduce((maxObj, currentObj) => {
    // 核心比较逻辑：直接解析时间字符串进行比较
    const currentTime = dayjs(currentObj[timeKey]);
    const maxTime = dayjs(maxObj[timeKey]);

    // 使用 isAfter 方法比较时间（Day.js 核心功能）
    return currentTime.isAfter(maxTime) ? currentObj : maxObj;
  });
}
watch(
  () => props.propValue?.tableData,
  newVal => {
    if (isVisualEditer) return;

    if (newVal && Array.isArray(newVal) === true) {
      try {
        const { destroySocket } = useWs({
          queryStr: "alarmWs",
          needRepeat: true, //需要多次建立
          onmessage: updateTable
        });
        destorySoc = destroySocket;
      } catch (e) {
        console.error(e);
      }
      let data = newVal.sort((a, b) => new Date(b.alarmTime).getTime() - new Date(a.alarmTime).getTime());
      if (pageType.value === "EQP") {
        data = data.filter(item => item.twinId === positionCode.value);
      }

      realTabelData.value = data;
      alertMessage();
    }
  },
  {
    immediate: true,
    deep: true
  }
);
onUnmounted(() => {
  PxMessage.closeAll();
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  if (destorySoc) destorySoc();
});
const handleAnalyse = async row => {
  const { roomId } = row;
  const data = await queryMonitor({ positionCode: roomId });
  isAnalyse.value = true;
  selectCameraOption.value = data as [];
  if (data.length > 0) {
    selectCamera.value = data[0].rtspUrl;
    cameraUrl.value = data[0].rtspUrl;
    // cameraUrl.value = "/data/ifp/file/file/1.mp4";
    getFlv();
  }
};
const handleDetail = row => {
  // const { alarmLevel, point, alarmType, alarmTime, alarmStatus } = row;
  // let parmas = {
  //   alarmLevel,
  //   point,
  //   alarmType,
  //   alarmTime
  // };
  // if (alarmStatus == "OFF") {
  //   parmas["active"] = "DONE";
  // }
  // const url = appendQueryParams("/all/alert/business", parmas);
  // router.push(url);

  alarmInfo.value = toRaw(row);

  alertShow.value = true;
};
function appendQueryParams(url, obj) {
  // 使用Array.prototype.reduce来构建查询字符串
  const queryString = Object.keys(obj)
    .filter(key => obj[key] !== null && obj[key] !== undefined)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join("&");

  // 如果查询字符串不为空，则将其拼接到URL后面
  if (queryString) {
    return `${url}?${queryString}`;
  }

  // 如果查询字符串为空，直接返回原URL
  return url;
}
const cameraChange = val => {
  cameraUrl.value = val;
  // cameraUrl.value = "/data/ifp/file/file/1.mp4";
  if (cameraUrl.value) getFlv();
};
const backToAlert = () => {
  destoryVideo();
  selectCamera.value = "";
  cameraUrl.value = "";
  isAnalyse.value = false;
};
onUnmounted(() => {
  destoryVideo();
  isAnalyse.value = false;
});
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" stripe :has-collapsed="propValue.collapsed">
    <div v-show="isCollapsed || !propValue.collapsed" class="list-warpper">
      <vxe-table
        v-show="!isAnalyse"
        height="224"
        :column-config="{ resizable: true }"
        :scroll-y="{ enabled: true, gt: 0 }"
        border="none"
        style="border: 0"
        :data="realTabelData"
        size="mini"
      >
        <vxe-column field="alarmLevel" title="级别" align="left" width="60">
          <template #default="{ row }">
            <px-tag style="color: #fff" round :color="tagBgColorList[row.alarmLevel]"> {{ tagLabelList[row.alarmLevel] }} </px-tag>
          </template>
        </vxe-column>
        <vxe-column field="alarmTime" title="发生时间" align="left" min-width="75">
          <template #default="{ row }">
            <px-tooltip class="box-item" effect="dark" :content="row.alarmTime" placement="top-end">
              <div class="w-[75%] overflow-ellipsis overflow-hidden whitespace-nowrap">{{ row.alarmTime }}</div>
            </px-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="point" title="点位" align="left" min-width="85">
          <template #default="{ row }">
            <px-tooltip class="box-item" effect="dark" :content="row.point" placement="top-end">
              <div class="w-[75%] overflow-ellipsis overflow-hidden whitespace-nowrap">{{ row.point }}</div>
            </px-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="position" title="位置" align="left" min-width="105">
          <template #default="{ row }">
            <div class="flex w=[100%] flex-wrap">
              <px-tooltip class="box-item" effect="dark" :content="dealposition(row)" placement="top-end">
                <div class="w-[75%] overflow-ellipsis overflow-hidden whitespace-nowrap">{{ dealposition(row) }}</div>
              </px-tooltip>
              <px-button type="primary" link icon="location" @click="handleLocation(row)" />
            </div>
          </template>
        </vxe-column>
        <vxe-column field="operate" title="操作" align="left" width="90" fixed="right">
          <template #default="{ row }">
            <px-button type="primary" size="small" class="btn-ml" link @click="handleAnalyse(row)">视频联动</px-button>
            <px-button type="primary" size="small" class="btn-ml" link @click="handleDetail(row)">详情</px-button>
          </template>
        </vxe-column>
      </vxe-table>
      <div v-if="isAnalyse">
        <px-form>
          <px-form-item label="请选择摄像头">
            <px-select v-model="selectCamera" placeholder="选择摄像头" size="small" @change="cameraChange">
              <px-option v-for="item in selectCameraOption" :key="item.id" :label="item.eqpName" :value="item.rtspUrl" />
            </px-select>
            <px-button type="primary" size="small" class="btn-ml" link @click="backToAlert">返回</px-button>
          </px-form-item>
        </px-form>
        <div class="flex w-[100%] h-[80%] justify-center">
          <div v-show="cameraUrl" ref="flvRef" />
          <px-empty v-show="!cameraUrl" :image-size="200" />
        </div>
      </div>
      <AlertDialog v-model:is-show="alertShow" :alarmInfo="alarmInfo" />
    </div>
  </leftCompWrapper>
</template>

<style lang="scss" scoped>
$listIcon: list-icon-;
$itemIcon: item-icon-;
$itemType: list-item-color-;

.list-warpper {
  width: 100%;

  .btn-ml {
    margin-left: 2px !important;
    font-size: 10px !important;
  }

  :deep(.px-table__cell) {
    padding-top: 2px !important;
    padding-bottom: 2px !important;
  }

  :deep(.cell) {
    padding-right: 2px !important;
    padding-left: 2px !important;
    font-size: 11px !important;
  }
}

:deep(.vxe-table) {
  /* 全局滚动条样式 */
  ::-webkit-scrollbar {
    width: 6px; /* 垂直滚动条宽度 */
    height: 6px; /* 水平滚动条高度 */
  }

  /* 滚动条轨道 */
  ::-webkit-scrollbar-track {
    background: #f5f5f5; /* Element Plus 风格的浅灰色轨道 */
    border-radius: 3px;
  }

  /* 滚动条滑块 */
  ::-webkit-scrollbar-thumb {
    background: #c0c4cc; /* Element Plus 中性色 */
    border-radius: 3px;
    transition: background-color 0.2s; /* 添加悬停动画 */
  }

  /* 悬停时滑块颜色加深 */
  ::-webkit-scrollbar-thumb:hover {
    background: #909399;
  }
}
</style>
